package com.demo.logistics.stockControl.data;

import java.util.ArrayList;

import com.demo.logistics.entities.Products;
import com.demo.logistics.entities.Stocks;
import com.demo.logistics.utils.DatabaseAdapter;

import android.app.Application;

public class AllDataModel extends Application implements IProductDataModel,
		IStockDataModel {

	private static AllDataModel myAllDataModel;
	private DatabaseAdapter db;
	//private static final int test = 4;
	
	@Override
	public void onCreate(){
		super.onCreate();
		myAllDataModel = this;
		db = new DatabaseAdapter(this);
		db.open();
	}
	
	public static AllDataModel getInstance(){
		return myAllDataModel;
	}
	
	public void closeDb(){
		if(db!=null){
			db.close();
		}
	}
	
	@Override
	public boolean addNewStock(Stocks newStock) {
		// TODO Auto-generated method stub
		Object[] items = {newStock.getProductName(), newStock.getQuantity(), newStock.getLorryPlateNo(), newStock.getDriverName(), null};
		int idx = db.insertEntry(items, DatabaseDescriptor.getStockTbl());
		if(idx>=0){
			return true;
		}
		return false;
	}

	@Override
	public boolean updateStockLocation(int id, String newLocation) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public ArrayList<Stocks> getAllStocks() {
		// TODO Auto-generated method stub
		ArrayList<Stocks> stockList = new ArrayList<Stocks>();
		ArrayList<Object[]> tempStockList = db.getAllEntries(DatabaseDescriptor.getStockTbl());
		for(int i=0; i<tempStockList.size(); i++){
			Object[] tempObj = tempStockList.get(i);
			stockList.add(new Stocks((Integer)tempObj[0], tempObj[1].toString(), (Integer)tempObj[2], tempObj[3].toString(), tempObj[4].toString(), tempObj[5].toString()));
		}
		return stockList;
	}

	@Override
	public boolean addNewProduct(Products newProd) {
		Object[] items = {newProd.getName(), newProd.getBrand(), newProd.getPrice()};
		int idx = db.insertEntry(items, DatabaseDescriptor.getProductTbl());
		if(idx>=0){
			return true;
		}
		return false;
	}

	@Override
	public ArrayList<Products> getAllProducts() {
		ArrayList<Products> productList = new ArrayList<Products>();
		if(db!=null){
			ArrayList<Object[]> prodList = db.getAllEntries(DatabaseDescriptor.getProductTbl());
			for(int i=0; i<prodList.size(); i++){
				Object[] tempObj = prodList.get(i);
				productList.add(new Products((Integer)tempObj[0], tempObj[1].toString(), tempObj[2].toString(), (Double)tempObj[3]));
			}
		}
		else{
			System.out.println("database is null");
		}
		return productList;
	}
}
